#include "LoadLevel.h"
#include "File.h"
#include "GameObject.h"
#include "ReportError.h"
#include "StringUtil.h"
#include "GameObjectFactory.h"
#include "Game.h"


GameObject* CreateObject(const std::string& typeName)
{
	return ObjectFactory::Instance()->Create(typeName);
}

bool LoadLevel(const std::string& filename)
{
	File f;

	//Open the File
	if(!f.OpenRead(filename))
	{
		ReportError("Cannot Open File!: " + __LINE__ + filename);
		return false;
	}
	//Read from file
	while (true)
	{
		//read a line from the file
		std::string	Str;
		if (!f.GetString(&Str))
		{
			break;
		}
		//use factory to make object
		GameObject* g = CreateObject(Str);
		if (!g)
		{
			ReportError("I don't know how to create this kind of object " + __LINE__ );
			break;
		}

		//Load in object ID
		int id = 0;
		if(!f.GetInteger(&id))
		{
			ReportError("I Expected an ID at this point " + __LINE__ );
			break;
		}
		g->SetId(id);

		//make the object load itself
		if (!g->Load(&f))
		{
			ReportError("Failed to load object: " + Str + ToString(id));
			break;
		}
		TheGame::Instance()->AddGameObject(id,g);
		//add the object to the container of game objects
		//(which lives in the game class)
	}
	return true;
}